<template>
  <el-row>
    <el-col :span="18" :offset="3">
      <el-row>
        <el-col :span="12" :offset="6" style="margin-top: 40px;">
          <el-steps :active="active" align-center>
            <el-step title="验证身份"></el-step>
            <el-step title="修改登录密码"></el-step>
            <el-step title="完成"></el-step>
          </el-steps>
        </el-col>
        <el-col :span="16" :offset="4" style="margin-top: 40px;">
          <el-form class="el-form-col" :model="model" label-position="left" ref="elForm" label-width="120px">
            <el-row class="row">
              <template v-if="active == 1">
                <template v-if="changeType == 'phone'">
                  <el-col :span="16" :offset="4">
                    <el-form-item label="登录手机">
                      <el-input readonly :value="starPhone"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="16" :offset="4">
                    <el-form-item key="code" prop="code" label="验证码" :rules="[
                    {required: true, message: '验证码必须', trigger: 'blur'}
                  ]">
                      <el-input v-model="model.code">
                        <template slot="append">
                          <el-button @click.prevent="getVerificationCode" :disabled="times > 0">{{ verificationCodeText
                            }}
                          </el-button>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </template>

                <template v-if="changeType == 'pwd'">
                  <el-col :span="16" :offset="4">
                    <el-form-item label="登陆账号">
                      <el-input readonly :value="loginName"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="16" :offset="4">
                    <el-form-item key="oldPwd" prop="oldPwd" label="旧密码" :rules="[
                    {required: true, message: '旧密码必须', trigger: 'blur'},
                    {validator: pwdValidate, message: '密码不正确', trigger: 'blur'}
                  ]">
                      <el-input v-if="showPassWord" v-model="model.oldPwd"></el-input>
                      <el-input v-else type="password" v-model="model.oldPwd"></el-input>
                    </el-form-item>
                  </el-col>
                </template>

              </template>
              <template v-if="active == 2">
                <el-col :span="16" :offset="4">
                  <el-form-item key="pwd" prop="pwd" label="请输入新密码" :rules="[
                      {required: true, message: '新密码必须且6到12位', trigger: 'blur', min: 6, max: 12}
                    ]">
                    <el-input type="password" v-model="model.pwd"/>
                  </el-form-item>
                </el-col>
                <el-col :span="16" :offset="4">
                  <el-form-item key="pwdTwo" prop="pwdTwo" label="再次确认" :rules="[
                    {required: true, message: '再次确认必须', trigger: 'blur'},
                    {validator: isSame, otherValue: model.pwd, message: '再次确认必须和新密码一致', trigger: 'blur'}
                  ]">
                    <el-input type="password" v-model="model.pwdTwo"/>
                  </el-form-item>
                </el-col>
              </template>
              <template v-if="active ==3">
                <el-col :span="16" :offset="4" class="text-center">
                  <el-form-item label-width="0px">
                    <p><i class="el-icon-success m--font-success font-light-blue" style="font-size: 80px"></i></p>
                    <p>修改成功</p>
                    <p>下次登录请使用新密码登录</p>
                  </el-form-item>
                </el-col>
              </template>
              <el-col class="text-center" :span="16" :offset="4">
                <el-button class="btn-block btn-lg" :loading="loading" type="primary" style="width:100%" @click.prevent="submit">
                  {{ active == 3 ? '确定' : '下一步' }}
                </el-button>

                <el-row v-if="isPrimary && active == 1">
                  <el-col :span="24">
                    <el-checkbox v-if="changeType == 'pwd'" style="line-height: 36px" class="pull-left"
                                 v-model="showPassWord">显示密码
                    </el-checkbox>
                    <el-button class="pull-right" @click.prevent="setChangeType" type="text">{{ changeTypeText }}
                    </el-button>
                    <div class="clearfix"></div>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>
<script>
import {isSame} from '@/utils/validate'
import {dotData, alert} from '@/utils'
import { logout } from '@/utils/ajax'
export default {
  name: 'myAccountChangePsw',
  data() {
    return {
      id: this.$route.params.id, // 用户id
      truePhone: this.$route.query.phone, // 用户phone
      loginName: this.$route.query.loginName, // 用户phone
      active: 1,
      model: {
        code: '',
        pwd: '',
        pwdTwo: '',
        oldPwd: ''
      },
      type: '',
      verificationCodeText: '获取验证码',
      getVerificationCodeButtonDisabled: false,
      config: {
        times: 60
      },
      isPrimary: false, // 是否是主账号
      changeType: 'phone', // ['phone', 'pwd]
      times: 0,
      loading: false,
      showPassWord: false
    }
  },
  computed: {
    starPhone() {
      let temp = this.truePhone || ''
      return temp.substr(0, 3) + '*****' + temp.substr(-3, 3)
    },
    changeTypeText() {
      switch (this.changeType) {
        case 'phone':
          return '切换为密码修改方式'
        case 'pwd':
          return '切换为短信验证方式'
      }
      return ''
    }
  },
  created() {
    this.setUserAdmin()
  },
  methods: {
    isSame,
    // 密码验证
    pwdValidate(rule, value, callback) {
      if (!value) { // 没有密码直接通过
        callback()
        return
      }
      this.$ajax.post('/ms-common-user/user/isUserPwd', {userId: this.id, pwd: value}).then(response => {
        if (response.success) {
          if (response.data) {
            callback()
          }
        }
        callback(new Error(rule.message))
      }).catch(_ => {
        callback(new Error(rule.message))
      })
    },
    // 判断师傅是主账号
    setUserAdmin() {
      this.$ajax.get('/ms-common-user/user/isUserAdmin').then(response => {
        if (response.success) {
          this.isPrimary = response.data || false
          if (!this.isPrimary) { // 如果不是主账号就只能密码修改
            this.changeType = 'pwd'
          }
        }
      })
    },
    // 获取验证码
    getVerificationCode() {
      this.times = this.config.times
      this.timeReduce() // 点击就开始倒计时,然后发送验证码(非：发送验证码成功过后再倒计时)
      this.$ajax.get('/ms-common-user/user/sendSms', {
        phone: this.truePhone,
        actionId: 'updatePwd'
      })
    },
    timeReduce() {
      if (this.times > 0) {
        this.verificationCodeText = this.times + 's'
        setTimeout(this.timeReduce, 1000)
        this.times -= 1
      } else {
        this.verificationCodeText = '获取验证码'
      }
    },
    // 验证验证码
    checkCode() {
      let checkData = {}
      checkData.actionId = 'updatePwd'
      checkData.phone = this.truePhone
      checkData.code = this.model.code
      this.loading = true
      this.$ajax.get('/ms-common-user/user/check-verification-code', checkData).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          this.active = 2
        } else {
          alert(dotData(response, 'message'))
        }
      }).finally(_ => {
        this.loading = false
      })
    },
    // 修改密码
    changePassword() {
      let data = {
        id: this.id,
        newPwd: this.model.pwd,
        core: this.model.code
      }
      this.loading = true
      this.$ajax.post('/ms-common-user/user/saveLoginPwd', data).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          this.active = 3
        }
      }).finally(_ => {
        this.loading = false
      })
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          return
        }
        if (this.active === 1) {
          if (this.changeType === 'phone') { // 验证码验证
            this.checkCode()
          } else if (this.changeType === 'pwd') { // 密码验证
            this.active = 2
          } else {
            alert('验证方式补正确')
          }
        } else if (this.active === 2) {
          this.changePassword()
        } else if (this.active === 3) {
          this.logout()
        }
      })
    },
    setChangeType() {
      switch (this.changeType) {
        case 'phone':
          this.changeType = 'pwd'
          break
        case 'pwd':
          this.changeType = 'phone'
          break
      }
    },
    logout() {
      logout()
    }
  }
}
</script>
